<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300">
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16 md:h-20">
          <!-- Logo -->
          <div class="flex items-center">
            <router-link to="/" class="flex items-center">
              <i class="fas fa-book text-primary text-2xl md:text-3xl mr-2"></i>
              <span class="text-xl md:text-2xl font-bold text-primary" style="font-weight: 700;">书香阁</span>
            </router-link>
          </div>

          <!-- 主导航 - 桌面版 -->
          <nav class="hidden md:flex items-center space-x-8">
            <router-link to="/home" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">首页</router-link>
            <router-link to="/category" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">分类</router-link>
            <router-link to="/bestseller" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">畅销榜</router-link>
            <router-link to="/news" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">资讯</router-link>
          </nav>

          <!-- 搜索框 -->
          <div class="hidden md:flex items-center flex-1 max-w-md mx-8">
            <div class="relative w-full flex">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入您喜欢的商品"
                class="search-input flex-1"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <i class="fas fa-search text-gray-400"></i>
                </template>
              </el-input>
              <button
                @click="handleSearch"
                class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
              >
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>

          <!-- 用户工具栏 -->
          <div class="flex items-center space-x-4">
            <button class="relative p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            <button
              @click="goToCart"
              class="relative p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-shopping-cart text-lg"></i>
              <span class="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full w-5 h-5 flex items-center justify-center cart-badge">{{ cartCount }}</span>
            </button>

            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="hidden md:block ml-2 text-gray-600">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item command="settings">设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 移动端菜单按钮 -->
            <button @click="toggleMobileMenu" class="md:hidden p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bars text-xl"></i>
            </button>
          </div>
        </div>

        <!-- 移动端搜索框 -->
        <div class="md:hidden pb-4">
          <div class="flex">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入您喜欢的商品"
              class="search-input flex-1"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search text-gray-400"></i>
              </template>
            </el-input>
            <button
              @click="handleSearch"
              class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
            >
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <div v-show="showMobileMenu" class="md:hidden bg-white border-t border-gray-100 shadow-lg">
        <div class="container mx-auto px-4 py-3 space-y-3">
          <router-link to="/home" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">首页</router-link>
          <router-link to="/category" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">分类</router-link>
          <router-link to="/bestseller" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">畅销榜</router-link>
          <router-link to="/news" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">资讯</router-link>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 返回按钮和页面标题 -->
      <div class="mb-6">
        <button @click="goBack" class="flex items-center text-gray-600 hover:text-primary transition-colors mb-4">
          <i class="fas fa-arrow-left mr-2"></i>
          返回
        </button>
        <h1 class="text-2xl font-bold text-gray-800">
          {{ isBuyNowMode ? '立即购买' : '订单详情' }}
        </h1>
      </div>

      <!-- 进度条 -->
      <div class="mb-8">
        <div class="flex items-center justify-center">
          <div class="flex items-center space-x-4 md:space-x-8">
            <!-- 步骤1: 选择收货地址 -->
            <div class="flex items-center">
              <div class="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center text-sm font-bold">
                1
              </div>
              <span class="ml-2 text-sm font-medium text-primary">选择收货地址</span>
            </div>
            
            <div class="w-16 h-0.5 bg-gray-300"></div>
            
            <!-- 步骤2: 确认订单信息 -->
            <div class="flex items-center">
              <div class="w-8 h-8 rounded-full bg-gray-300 text-gray-600 flex items-center justify-center text-sm font-bold">
                2
              </div>
              <span class="ml-2 text-sm font-medium text-gray-600">确认订单信息</span>
            </div>
            
            <div class="w-16 h-0.5 bg-gray-300"></div>
            
            <!-- 步骤3: 订单支付完成 -->
            <div class="flex items-center">
              <div class="w-8 h-8 rounded-full bg-gray-300 text-gray-600 flex items-center justify-center text-sm font-bold">
                3
              </div>
              <span class="ml-2 text-sm font-medium text-gray-600">订单支付完成</span>
            </div>
            
            <div class="w-16 h-0.5 bg-gray-300"></div>
            
            <!-- 步骤4: 确认收货 -->
            <div class="flex items-center">
              <div class="w-8 h-8 rounded-full bg-gray-300 text-gray-600 flex items-center justify-center text-sm font-bold">
                4
              </div>
              <span class="ml-2 text-sm font-medium text-gray-600">确认收货</span>
            </div>
            
            <div class="w-16 h-0.5 bg-gray-300"></div>
            
            <!-- 步骤5: 评价 -->
            <div class="flex items-center">
              <div class="w-8 h-8 rounded-full bg-gray-300 text-gray-600 flex items-center justify-center text-sm font-bold">
                5
              </div>
              <span class="ml-2 text-sm font-medium text-gray-600">评价</span>
            </div>
          </div>
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧内容 -->
        <div class="lg:col-span-2 space-y-6">
          <!-- 选择地址 -->
          <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 class="text-lg font-bold text-gray-800 mb-4">选择地址</h2>
            
            <!-- 加载中状态 -->
            <div v-if="isAddressLoading" class="flex justify-center py-8">
              <el-skeleton style="width: 100%" :rows="3" animated />
            </div>
            
            <!-- 无地址提示 -->
            <div v-else-if="addresses.length === 0" class="text-center py-8">
              <i class="fas fa-map-marker-alt text-gray-400 text-4xl mb-2"></i>
              <p class="text-gray-500 mb-4">您还没有添加收货地址</p>
              <el-button type="primary" @click="showAddAddressDialog">添加新地址</el-button>
            </div>
            
            <!-- 地址列表 -->
            <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div
                v-for="address in addresses"
                :key="address.id"
                @click="selectAddress(address)"
                :class="[
                  'border-2 rounded-lg p-4 cursor-pointer transition-all duration-200 relative group',
                  selectedAddress?.id === address.id 
                    ? 'border-primary bg-primary/5' 
                    : 'border-gray-200 hover:border-primary/50'
                ]"
              >
                <div class="flex items-start justify-between">
                  <div class="flex-1">
                    <div class="flex items-center mb-2">
                      <span class="font-medium text-gray-800">{{ address.name }}</span>
                      <span class="ml-2 text-sm text-gray-600">{{ address.phone }}</span>
                      <span v-if="address.isDefault" class="ml-2 px-2 py-0.5 bg-primary text-white text-xs rounded">默认</span>
                      <span v-if="address.tag" class="ml-2 px-2 py-0.5 bg-gray-100 text-gray-600 text-xs rounded">
                        {{ address.tag === 'home' ? '家' : address.tag === 'company' ? '公司' : 
                           address.tag === 'school' ? '学校' : '其他' }}
                      </span>
                    </div>
                    <p class="text-sm text-gray-600 mb-1">{{ address.fullAddress }}</p>
                    <p class="text-xs text-gray-500">{{ address.province }} {{ address.city }} {{ address.district }}</p>
                  </div>
                  <div v-if="selectedAddress?.id === address.id" class="text-primary">
                    <i class="fas fa-check-circle"></i>
                  </div>
                </div>
                
                <!-- 地址操作按钮 -->
                <div class="address-actions absolute right-2 bottom-2 flex items-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                  <el-button 
                    v-if="!address.isDefault"
                    @click.stop="setDefaultAddress(address.id)" 
                    type="text" 
                    size="small"
                  >
                    设为默认
                  </el-button>
                  <el-button 
                    @click.stop="showEditAddressDialog(address)" 
                    type="text" 
                    size="small"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    @click.stop="deleteAddress(address.id)"
                    type="text" 
                    size="small"
                    class="text-red-500"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
            
            <button @click="showAddAddressDialog" class="mt-4 text-primary hover:text-primary-dark transition-colors">
              <i class="fas fa-plus mr-1"></i>
              添加新地址
            </button>
          </div>

          <!-- 确认订单信息 -->
          <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div class="flex items-center mb-4">
              <i class="fas fa-user-circle text-primary mr-2"></i>
              <h2 class="text-lg font-bold text-gray-800">确认订单信息</h2>
            </div>

            <!-- 桌面端表格 -->
            <div class="hidden md:block">
              <!-- 表格头部 -->
              <div class="border border-gray-200 rounded-t-lg order-table-header">
                <div class="grid grid-cols-12 gap-4 px-4 py-3 text-sm font-medium text-gray-700">
                  <div class="col-span-2 text-center">商品图片</div>
                  <div class="col-span-3">商品名称</div>
                  <div class="col-span-2 text-center">单价</div>
                  <div class="col-span-2 text-center">数量</div>
                  <div class="col-span-3 text-center">小计</div>
                </div>
              </div>

              <!-- 商品列表 -->
              <div class="border-l border-r border-gray-200">
                <div
                  v-for="(item, index) in cartItems"
                  :key="item.id"
                  :class="[
                    'grid grid-cols-12 gap-4 px-4 py-4 items-center border-b border-gray-200 order-table-row',
                    index % 2 === 0 ? 'bg-white' : 'bg-gray-50/50'
                  ]"
                >
                  <!-- 商品图片 -->
                  <div class="col-span-2 flex justify-center">
                                      <img
                    :src="getImageUrl(item.cover)"
                    :alt="item.title"
                    class="w-12 h-16 object-cover rounded shadow-sm order-item-image"
                  >
                  </div>

                  <!-- 商品名称 -->
                  <div class="col-span-3">
                    <h3 class="font-medium text-gray-800 text-sm mb-1 line-clamp-2">{{ item.title }}</h3>
                    <p class="text-xs text-gray-500">{{ item.author }}</p>
                  </div>

                  <!-- 单价 -->
                  <div class="col-span-2 text-center">
                    <span class="text-primary font-bold">¥{{ item.price.toFixed(2) }}</span>
                  </div>

                  <!-- 数量 -->
                  <div class="col-span-2 flex items-center justify-center">
                    <div class="flex items-center border border-gray-300 rounded-lg quantity-control">
                      <button
                        @click="decreaseQuantity(item)"
                        :disabled="item.quantity <= 1"
                        class="w-8 h-8 flex items-center justify-center rounded-l-lg"
                      >
                        <i class="fas fa-minus text-xs text-gray-600"></i>
                      </button>
                      <span class="w-12 h-8 flex items-center justify-center font-medium border-l border-r border-gray-300 bg-gray-50">{{ item.quantity }}</span>
                      <button
                        @click="increaseQuantity(item)"
                        class="w-8 h-8 flex items-center justify-center rounded-r-lg"
                      >
                        <i class="fas fa-plus text-xs text-gray-600"></i>
                      </button>
                    </div>
                  </div>

                  <!-- 小计 -->
                  <div class="col-span-3 text-center">
                    <span class="font-bold text-primary text-lg">{{ (item.price * item.quantity).toFixed(2) }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 移动端卡片布局 -->
            <div class="md:hidden space-y-4">
              <div
                v-for="item in cartItems"
                :key="item.id"
                class="border border-gray-200 rounded-lg p-4 bg-white shadow-sm"
              >
                <div class="flex items-start space-x-4">
                  <img
                    :src="getImageUrl(item.cover)"
                    :alt="item.title"
                    class="w-16 h-20 object-cover rounded shadow-sm flex-shrink-0"
                  >
                  <div class="flex-1 min-w-0">
                    <h3 class="font-medium text-gray-800 text-sm mb-1 line-clamp-2">{{ item.title }}</h3>
                    <p class="text-xs text-gray-500 mb-3">{{ item.author }}</p>

                    <div class="grid grid-cols-3 gap-2 text-sm">
                      <div class="text-center">
                        <div class="text-gray-500 text-xs mb-1">单价</div>
                        <div class="text-primary font-bold">¥{{ item.price.toFixed(2) }}</div>
                      </div>
                      <div class="text-center">
                        <div class="text-gray-500 text-xs mb-1">数量</div>
                        <div class="flex items-center justify-center">
                          <div class="flex items-center border border-gray-300 rounded quantity-control">
                            <button
                              @click="decreaseQuantity(item)"
                              :disabled="item.quantity <= 1"
                              class="w-6 h-6 flex items-center justify-center rounded-l"
                            >
                              <i class="fas fa-minus text-xs text-gray-600"></i>
                            </button>
                            <span class="w-8 h-6 flex items-center justify-center font-medium text-xs border-l border-r border-gray-300 bg-gray-50">{{ item.quantity }}</span>
                            <button
                              @click="increaseQuantity(item)"
                              class="w-6 h-6 flex items-center justify-center rounded-r"
                            >
                              <i class="fas fa-plus text-xs text-gray-600"></i>
                            </button>
                          </div>
                        </div>
                      </div>
                      <div class="text-center">
                        <div class="text-gray-500 text-xs mb-1">小计</div>
                        <div class="font-bold text-primary">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 给卖家留言 -->
            <div class="mt-4 text-sm text-gray-600">
              给卖家留言：
              <el-input
                v-model="orderNote"
                type="textarea"
                :rows="3"
                placeholder="选填，请先和商家协商一致"
                class="mt-2"
              />
            </div>
          </div>

          <!-- 支付方式 -->
          <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 class="text-lg font-bold text-gray-800 mb-4">支付方式</h2>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div
                v-for="payment in paymentMethods"
                :key="payment.id"
                @click="selectPayment(payment)"
                :class="[
                  'border-2 rounded-lg p-4 cursor-pointer transition-all duration-200 flex items-center',
                  selectedPayment?.id === payment.id 
                    ? 'border-primary bg-primary/5' 
                    : 'border-gray-200 hover:border-primary/50'
                ]"
              >
                <img :src="payment.icon" :alt="payment.name" class="w-12 h-12 mr-3">
                <div class="flex-1">
                  <div class="font-medium text-gray-800">{{ payment.name }}</div>
                  <div class="text-sm text-gray-500">{{ payment.description }}</div>
                </div>
                <div v-if="selectedPayment?.id === payment.id" class="text-primary">
                  <i class="fas fa-check-circle"></i>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧订单摘要 -->
        <div class="lg:col-span-1">
          <div class="bg-white rounded-xl shadow-lg border border-gray-200 sticky top-24">
            <div class="p-6 border-b border-gray-100">
              <h2 class="text-xl font-bold text-gray-800">合计</h2>
            </div>

            <div class="p-6 space-y-4">
              <div class="space-y-3">
                <div class="flex justify-between text-base">
                  <span class="text-gray-600">商品总价</span>
                  <span class="font-medium">¥{{ subtotal }}</span>
                </div>
                <div class="flex justify-between text-base">
                  <span class="text-gray-600">运费</span>
                  <span class="font-medium">
                    <span v-if="shipping === 0" class="text-green-600">免运费</span>
                    <span v-else>¥{{ shipping.toFixed(2) }}</span>
                  </span>
                </div>
              </div>

              <div class="border-t border-gray-200 pt-4">
                <div class="flex justify-between text-xl font-bold">
                  <span class="text-gray-800">总计</span>
                  <span class="text-primary">¥{{ total.toFixed(2) }}</span>
                </div>
              </div>

              <div class="pt-4">
                <button
                  @click="submitOrder"
                  :disabled="!selectedAddress || !selectedPayment"
                  :class="[
                    'w-full py-4 rounded-lg font-bold text-lg transition-all duration-300',
                    selectedAddress && selectedPayment
                      ? 'bg-primary text-white hover:bg-primary-dark hover:shadow-lg transform hover:-translate-y-0.5'
                      : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                  ]"
                >
                  <i class="fas fa-credit-card mr-2"></i>
                  下单支付
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部页脚 -->
    <footer class="bg-gray-900 text-white py-10 mt-16">
      <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
          <!-- 关于我们 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">关于书香阁</h3>
            <p class="text-gray-400 text-sm">
              书香阁是专业的网上书店，提供超过10万种图书在线购买，支持快递配送和自提服务，让阅读触手可及。
            </p>
          </div>

          <!-- 快捷链接 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">快捷链接</h3>
            <ul class="space-y-2 text-sm">
              <li><router-link to="/category" class="text-gray-400 hover:text-primary">分类浏览</router-link></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">热门排行</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">最新上架</a></li>
            </ul>
          </div>

          <!-- 客户服务 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">客户服务</h3>
            <ul class="space-y-2 text-sm">
              <li><a href="#" class="text-gray-400 hover:text-primary">配送方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">支付方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">联系我们</a></li>
            </ul>
          </div>

          <!-- 联系方式 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">联系我们</h3>
            <ul class="space-y-3 text-sm">
              <li class="flex items-center">
                <i class="fas fa-phone text-primary mr-3"></i>
                <span class="text-gray-400">400-800-1234</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-envelope text-primary mr-3"></i>
                <span class="text-gray-400">service@bookstore.com</span>
              </li>
            </ul>
          </div>
        </div>

        <!-- 版权信息 -->
        <div class="border-t border-gray-800 mt-8 pt-8 text-center">
          <div class="text-gray-500 text-sm">
            © {{ new Date().getFullYear() }} 书香阁 版权所有
          </div>
        </div>
      </div>
    </footer>

    <!-- 添加/编辑地址对话框 -->
    <el-dialog
      :title="addressDialogType === 'add' ? '添加新地址' : '编辑地址'"
      v-model="addressDialogVisible"
      width="500px"
      @closed="addressFormRef = null"
    >
      <el-form
        ref="addressFormRef"
        :model="addressForm"
        :rules="addressFormRules"
        label-width="100px"
      >
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addressForm.name" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-select v-model="addressForm.province" placeholder="请选择省份" @change="addressForm.city = ''">
            <el-option v-for="item in provinces" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="addressForm.city" placeholder="请选择城市" @change="addressForm.district = ''">
            <el-option v-for="item in cities" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区县" prop="district">
          <el-select v-model="addressForm.district" placeholder="请选择区县">
            <el-option v-for="item in districts" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="addressForm.detail" type="textarea" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-select v-model="addressForm.tag" placeholder="请选择地址标签">
            <el-option label="家" value="home"></el-option>
            <el-option label="公司" value="company"></el-option>
            <el-option label="学校" value="school"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设为默认" prop="isDefault">
          <el-switch v-model="addressForm.isDefault"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddressForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { useOrderStore } from '@/stores/order'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userAPI } from '@/api/user' // 引入用户API
import { orderAPI } from '@/api/order' // 引入订单API

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()
const orderStore = useOrderStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const orderNote = ref('')
const selectedAddress = ref(null)
const selectedPayment = ref(null)
const addresses = ref([]) // 改为ref，用于存储从API获取的地址
const isAddressLoading = ref(false) // 添加加载状态

// 地址管理相关
const addressDialogVisible = ref(false)
const addressForm = reactive({
  id: null,
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  tag: 'home',
  isDefault: false
})
const addressDialogType = ref('add') // 'add'或'edit'
const addressFormRules = {
  name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  province: [{ required: true, message: '请选择省份', trigger: 'change' }],
  city: [{ required: true, message: '请选择城市', trigger: 'change' }],
  district: [{ required: true, message: '请选择区县', trigger: 'change' }],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在5到100个字符之间', trigger: 'blur' }
  ]
}

const addressFormRef = ref(null)

// 省市区数据（简化版）
const provinces = ref(['北京市', '上海市', '广东省', '江苏省', '浙江省', '四川省', '湖北省', '湖南省', '福建省', '河南省'])
const citiesMap = reactive({
  '北京市': ['北京市'],
  '上海市': ['上海市'],
  '广东省': ['广州市', '深圳市', '佛山市', '珠海市', '东莞市', '中山市', '惠州市'],
  '江苏省': ['南京市', '苏州市', '无锡市', '常州市', '南通市', '扬州市', '镇江市'],
  '浙江省': ['杭州市', '宁波市', '温州市', '嘉兴市', '绍兴市', '金华市', '台州市'],
  '四川省': ['成都市', '绵阳市', '德阳市', '自贡市', '泸州市', '南充市', '宜宾市'],
  '湖北省': ['武汉市', '宜昌市', '襄阳市', '荆州市', '黄石市', '荆门市', '鄂州市'],
  '湖南省': ['长沙市', '株洲市', '湘潭市', '衡阳市', '岳阳市', '常德市', '益阳市'],
  '福建省': ['福州市', '厦门市', '泉州市', '莆田市', '漳州市', '龙岩市', '三明市'],
  '河南省': ['郑州市', '洛阳市', '开封市', '新乡市', '许昌市', '平顶山市', '安阳市'],
})
const districtsMap = reactive({
  '北京市': {
    '北京市': ['东城区', '西城区', '朝阳区', '海淀区', '丰台区', '石景山区', '顺义区', '通州区', '昌平区']
  },
  '上海市': {
    '上海市': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '杨浦区', '浦东新区', '闵行区']
  },
  '广东省': {
    '广州市': ['越秀区', '荔湾区', '海珠区', '天河区', '白云区', '黄埔区', '花都区', '番禺区', '南沙区'],
    '深圳市': ['福田区', '罗湖区', '南山区', '宝安区', '龙岗区', '盐田区', '龙华区', '坪山区', '光明区'],
    // 其他城市的区县数据
  },
  // 其他省份的城市区县数据
})

// 计算属性获取当前省份的城市列表
const cities = computed(() => {
  return addressForm.province ? citiesMap[addressForm.province] || [] : []
})

// 计算属性获取当前城市的区县列表
const districts = computed(() => {
  if (!addressForm.province || !addressForm.city) return []
  return (districtsMap[addressForm.province] && districtsMap[addressForm.province][addressForm.city]) || []
})

// 计算属性
const cartItems = computed(() => cartStore.checkoutItems)
const cartCount = computed(() => cartStore.cartCount)
const subtotal = computed(() => cartStore.checkoutTotal)
const isBuyNowMode = computed(() => cartStore.isBuyNowMode)

const shipping = computed(() => {
  return parseFloat(subtotal.value) >= 99 ? 0 : 10 // 满99免运费
})

const total = computed(() => {
  return parseFloat(subtotal.value) + shipping.value
})

// 支付方式数据
const paymentMethods = reactive([
  {
    id: 1,
    name: '支付宝',
    description: 'ALIPAY',
    icon: 'https://img.icons8.com/external-tal-revivo-color-tal-revivo/48/external-alipay-a-third-party-mobile-and-online-payment-platform-logo-color-tal-revivo.png'
  },
  {
    id: 2,
    name: '微信支付',
    description: 'WeChat Pay',
    icon: 'https://img.icons8.com/plasticine/48/weixing.png'
  },
  {
    id: 3,
    name: '银联支付',
    description: 'UnionPay',
    icon: 'https://img.icons8.com/color/48/unionpay.png'
  }
])

// 方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    ElMessage.info(`搜索功能开发中，搜索关键词：${searchKeyword.value}`)
  }
}

const goBack = () => {
  router.go(-1)
}

const goToCart = () => {
  router.push('/cart')
}

const selectAddress = (address) => {
  selectedAddress.value = address
}

const selectPayment = (payment) => {
  selectedPayment.value = payment
}

const increaseQuantity = async (item) => {
  try {
    if (isBuyNowMode.value) {
      cartStore.updateBuyNowQuantity(item.id, item.quantity + 1)
      ElMessage.success(`已增加《${item.title}》的数量`)
    } else {
      await cartStore.updateQuantity(item.id, item.quantity + 1)
      // 消息提示已在store中处理
    }
  } catch (error) {
    console.error('增加数量失败:', error)
  }
}

const decreaseQuantity = async (item) => {
  if (item.quantity > 1) {
    try {
      if (isBuyNowMode.value) {
        cartStore.updateBuyNowQuantity(item.id, item.quantity - 1)
        ElMessage.success(`已减少《${item.title}》的数量`)
      } else {
        await cartStore.updateQuantity(item.id, item.quantity - 1)
        // 消息提示已在store中处理
      }
    } catch (error) {
      console.error('减少数量失败:', error)
    }
  } else {
    ElMessage.warning('商品数量不能少于1')
  }
}

const submitOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  if (!selectedPayment.value) {
    ElMessage.warning('请选择支付方式')
    return
  }

  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，无法下单')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认使用${selectedPayment.value.name}支付 ¥${total.value.toFixed(2)} 吗？`,
      '确认支付',
      {
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        type: 'info',
      }
    )

    // 显示加载状态
    const loadingMessage = ElMessage({
      message: '订单提交中，请稍候...',
      type: 'info',
      duration: 0
    })

    // 准备创建订单的数据
    const orderData = {
      // 使用与后端匹配的字段名
      totalAmount: total.value,
      actualAmount: total.value, // 实际支付金额，目前与总金额相同
      discountAmount: 0,  // 折扣金额，目前没有折扣
      shippingFee: shipping.value,
      address: {
        id: selectedAddress.value.id,
        receiverName: selectedAddress.value.name,
        receiverPhone: selectedAddress.value.phone,
        fullAddress: selectedAddress.value.fullAddress
      },
      remark: orderNote.value || '',
      items: cartItems.value.map(item => ({
        bookId: item.id,
        title: item.title,
        cover: item.cover,
        price: item.price,
        quantity: item.quantity
      }))
    }

    try {
      // 调用前记录请求数据，便于调试
      console.log('提交订单数据:', JSON.stringify(orderData))
      
      // 调用后端 API 创建订单
      const response = await orderAPI.createOrder(orderData)
      console.log('订单创建响应:', response)
      
      // 检查后端响应
      if (response && response.data) {
        const serverOrder = response.data;
        
        // 订单创建成功后，立即调用支付API
        try {
          // 调用支付API更新订单状态
          await orderAPI.payOrder(serverOrder.orderId, { 
            paymentType: selectedPayment.value.id // 确保传递正确的支付方式ID
          })
          console.log('支付API调用成功，支付方式:', selectedPayment.value.name)
        } catch (payError) {
          console.error('自动支付失败:', payError)
          // 即使自动支付失败，仍然继续流程，因为订单已创建
        }
        
        // 关闭加载消息
        loadingMessage.close()
        
        // 在前端 store 中也创建对应的订单（用于本地显示）
        const newOrder = orderStore.createOrder(
          cartItems.value,
          total.value,
          selectedPayment.value.id
        )

        // 根据模式清空不同的商品列表
        if (isBuyNowMode.value) {
          cartStore.clearBuyNowItems()
        } else {
          cartStore.clearCart()
        }

        ElMessage.success(`支付成功！订单 ${serverOrder.orderNo || newOrder.orderNumber} 已生成`)
        router.push('/orders')
      } else {
        throw new Error('服务器返回数据格式不正确')
      }
    } catch (error) {
      console.error('创建订单失败:', error)
      // 打印更详细的错误信息
      if (error.response) {
        console.error('错误响应数据:', error.response.data)
        console.error('错误状态码:', error.response.status)
      } else if (error.data) {
        console.error('业务错误数据:', error.data)
      }
      loadingMessage.close()
      
      // 显示更具体的错误信息
      let errorMsg = '服务器错误';
      if (error.response?.data?.message) {
        errorMsg = error.response.data.message;
      } else if (error.message) {
        errorMsg = error.message;
      } else if (typeof error === 'string') {
        errorMsg = error;
      }
      
      ElMessage.error(`创建订单失败: ${errorMsg}`)
      
      // 回退到前端创建订单（作为备用方案）
      ElMessage.warning('连接服务器失败，将创建离线订单')
      
      setTimeout(() => {
        // 使用前端 store 创建订单
        const newOrder = orderStore.createOrder(
          cartItems.value,
          total.value,
          selectedPayment.value.id
        )
        
        // 根据模式清空不同的商品列表
        if (isBuyNowMode.value) {
          cartStore.clearBuyNowItems()
        } else {
          cartStore.clearCart()
        }
        
        ElMessage.success(`订单 ${newOrder.orderNumber} 已创建（离线模式）`)
        router.push('/orders')
      }, 1000)
    }
  } catch {
    // 用户取消支付
  }
}

// 从数据库获取用户地址列表
const fetchUserAddresses = async () => {
  isAddressLoading.value = true
  try {
    // 获取用户地址列表
    const result = await userAPI.getUserAddressList()
    console.log('获取到的地址数据:', result)
    
    // 根据API实现，这里直接返回data属性
    let addressList = []
    if (result && result.data) {
      // 可能是数组或嵌套对象
      if (Array.isArray(result.data)) {
        addressList = result.data
      } else if (typeof result.data === 'object') {
        // 尝试不同的数据结构
        if (Array.isArray(result.data.records)) {
          addressList = result.data.records
        } else if (Array.isArray(result.data.data)) {
          addressList = result.data.data
        } else if (result.data.list && Array.isArray(result.data.list)) {
          addressList = result.data.list
        }
      }
    }
    
    console.log('解析后的地址列表:', addressList)
    
    // 确保地址数据结构正确
    addresses.value = addressList.map(addr => {
      return {
        id: addr.id,
        name: addr.name || addr.receiverName || '',
        phone: addr.phone || addr.receiverPhone || '',
        province: addr.province || '',
        city: addr.city || '',
        district: addr.district || '',
        detail: addr.detail || addr.addressDetail || '',
        fullAddress: addr.fullAddress || `${addr.province || ''}${addr.city || ''}${addr.district || ''}${addr.detail || addr.addressDetail || ''}`,
        isDefault: addr.isDefault || addr.defaultStatus === 1,
        tag: addr.tag || 'home'
      }
    })
    
    // 如果有地址，默认选择默认地址或第一个地址
    if (addresses.value.length > 0) {
      const defaultAddress = addresses.value.find(addr => addr.isDefault) || addresses.value[0]
      selectedAddress.value = defaultAddress
    } else {
      ElMessage.warning('您还没有添加收货地址，请先添加地址')
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    const errorMessage = error.message || '请稍后再试'
    ElMessage.error(`获取地址列表失败：${errorMessage}`)
  } finally {
    isAddressLoading.value = false
  }
}

// 显示添加地址对话框
const showAddAddressDialog = () => {
  addressDialogType.value = 'add'
  // 重置表单
  Object.keys(addressForm).forEach(key => {
    addressForm[key] = key === 'isDefault' ? false : ''
  })
  addressForm.tag = 'home'
  addressDialogVisible.value = true
}

// 显示编辑地址对话框
const showEditAddressDialog = (address) => {
  addressDialogType.value = 'edit'
  // 填充表单数据
  Object.keys(addressForm).forEach(key => {
    addressForm[key] = address[key]
  })
  addressDialogVisible.value = true
}

// 提交地址表单
const submitAddressForm = async () => {
  if (!addressFormRef.value) return
  
  try {
    await addressFormRef.value.validate()
    
    // 准备提交的数据，添加fullAddress字段
    const submitData = { ...addressForm }
    submitData.fullAddress = `${submitData.province}${submitData.city}${submitData.district}${submitData.detail}`
    
    // 根据后端API可能需要的字段进行适配
    const apiData = {
      ...submitData,
      // 添加可能的字段映射
      receiverName: submitData.name,
      receiverPhone: submitData.phone,
      addressDetail: submitData.detail,
      defaultStatus: submitData.isDefault ? 1 : 0
    }
    
    console.log('提交的地址数据:', apiData)
    
    // 添加或更新地址
    if (addressDialogType.value === 'add') {
      await userAPI.addUserAddress(apiData)
      ElMessage.success('添加地址成功')
    } else {
      await userAPI.updateUserAddress(submitData.id, apiData)
      ElMessage.success('更新地址成功')
    }
    
    addressDialogVisible.value = false
    await fetchUserAddresses() // 重新获取地址列表
  } catch (error) {
    console.error('地址表单提交失败:', error)
    const errorMessage = error.message || '请检查表单内容'
    ElMessage.error(`提交失败：${errorMessage}`)
  }
}

// 删除地址
const deleteAddress = async (addressId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个地址吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    console.log('删除地址:', addressId)
    await userAPI.deleteUserAddress(addressId)
    ElMessage.success('删除地址成功')
    await fetchUserAddresses()
  } catch (error) {
    // 区分是用户取消操作还是API错误
    if (error !== 'cancel' && error.toString() !== 'Error: cancel') {
      console.error('删除地址失败:', error)
      const errorMessage = error.message || '请稍后再试'
      ElMessage.error(`删除地址失败：${errorMessage}`)
    }
  }
}

// 设为默认地址
const setDefaultAddress = async (addressId) => {
  try {
    console.log('设置默认地址:', addressId)
    await userAPI.setDefaultAddress(addressId)
    ElMessage.success('已设为默认地址')
    await fetchUserAddresses()
  } catch (error) {
    console.error('设置默认地址失败:', error)
    const errorMessage = error.message || '请稍后再试'
    ElMessage.error(`设置默认地址失败：${errorMessage}`)
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理登出
const handleLogout = () => {
  userStore.logout()
  ElMessage.success('已退出登录')
  router.push('/login')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 生命周期
onMounted(() => {
  // 检查是否有商品需要结算
  if (cartItems.value.length === 0) {
    if (isBuyNowMode.value) {
      ElMessage.warning('立即购买商品信息丢失，请重新选择')
      router.push('/home')
    } else {
      ElMessage.warning('购物车为空，请先添加商品')
      router.push('/cart')
    }
    return
  }

  // 加载用户地址
  fetchUserAddresses()

  // 默认选择第一个支付方式
  if (paymentMethods.length > 0) {
    selectedPayment.value = paymentMethods[0]
  }
})
</script>

<style scoped>
/* 自定义样式 */
:root {
  --primary: #FF6B8A;
  --primary-light: #FFB3C6;
  --primary-dark: #E55A7A;
  --secondary: #FFF0F3;
  --accent: #FF8FA3;
  --success: #4CAF50;
  --warning: #FF9800;
  --info: #2196F3;
  --dark: #2D3748;
  --gray: #718096;
  --light-gray: #F7FAFC;
  --white: #FFFFFF;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #606266;
  transition: color 0.3s ease;
}

.el-dropdown-link:hover {
  color: var(--primary);
}

/* 搜索框样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 9999px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: var(--primary);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2);
}

/* 搜索按钮样式 */
.search-button {
  background-color: #FF6B8B !important;
}

.search-button:hover {
  background-color: rgba(255, 107, 139, 0.8) !important;
}

/* 主题色定义 */
.text-primary {
  color: rgb(255, 107, 139) !important;
}

.bg-primary {
  background-color: #FF6B8B !important;
}

.border-primary {
  border-color: #FF6B8B !important;
}

.hover\:border-primary:hover {
  border-color: #FF6B8B !important;
}

.hover\:text-primary:hover {
  color: #FF6B8B !important;
}

.bg-primary-dark {
  background-color: #E55A7A !important;
}

.hover\:bg-primary-dark:hover {
  background-color: #E55A7A !important;
}

.bg-primary\/5 {
  background-color: rgba(255, 107, 139, 0.05) !important;
}

.border-primary\/50 {
  border-color: rgba(255, 107, 139, 0.5) !important;
}

.hover\:border-primary\/50:hover {
  border-color: rgba(255, 107, 139, 0.5) !important;
}

/* 进度条样式 */
.progress-step {
  transition: all 0.3s ease;
}

.progress-step.active {
  color: var(--primary);
}

.progress-step.active .step-circle {
  background-color: var(--primary);
  color: white;
}

/* 地址卡片样式 */
.address-card {
  transition: all 0.2s ease;
}

.address-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.address-card.selected {
  border-color: var(--primary);
  background-color: rgba(255, 107, 139, 0.05);
}

/* 地址操作按钮 */
.address-actions {
  transition: opacity 0.2s ease;
}

.group:hover .address-actions {
  opacity: 1 !important;
}

/* 支付方式卡片样式 */
.payment-card {
  transition: all 0.2s ease;
}

.payment-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.payment-card.selected {
  border-color: var(--primary);
  background-color: rgba(255, 107, 139, 0.05);
}

/* 订单商品卡片样式 */
.order-item {
  transition: all 0.2s ease;
}

.order-item:hover {
  background-color: #f9fafb;
}

/* 数量控制按钮样式 */
.quantity-control {
  transition: all 0.2s ease;
}

.quantity-control button {
  transition: all 0.2s ease;
  border: none;
  background: transparent;
}

.quantity-control button:hover {
  background-color: #f3f4f6;
  transform: scale(1.1);
}

.quantity-control button:active {
  transform: scale(0.95);
}

.quantity-control button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-control button:disabled:hover {
  background: transparent;
  transform: none;
}

/* 提交按钮样式 */
.submit-btn {
  position: relative;
  overflow: hidden;
}

.submit-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.submit-btn:hover::before {
  left: 100%;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .container {
    padding-left: 1rem;
    padding-right: 1rem;
  }

  .progress-step {
    flex-direction: column;
    text-align: center;
  }

  .progress-step span {
    margin-left: 0;
    margin-top: 0.5rem;
  }

  .grid.lg\\:grid-cols-3 {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }

  .lg\\:col-span-2,
  .lg\\:col-span-1 {
    grid-column: span 1;
  }

  .sticky {
    position: relative;
    top: auto;
  }
}

.cart-badge {
  z-index: 10;
  transform: translate(25%, -25%);
  min-width: 18px;
  height: 18px;
}

/* 文本截断 */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 订单信息表格样式 */
.order-table-header {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-bottom: 2px solid #e2e8f0;
}

.order-table-row {
  transition: all 0.2s ease;
}

.order-table-row:hover {
  background-color: #fef7f0 !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-item-image {
  transition: transform 0.2s ease;
}

.order-item-image:hover {
  transform: scale(1.05);
}

/* 商品总价区域样式 */
.order-summary {
  background: linear-gradient(135deg, #fff5f5 0%, #fef2f2 100%);
  border-top: 2px solid #fecaca;
}

/* 移动端表格适配 */
@media (max-width: 768px) {
  .order-table-mobile {
    display: block;
  }

  .order-table-mobile .grid {
    display: block;
    border: 1px solid #e5e7eb;
    border-radius: 0.5rem;
    margin-bottom: 1rem;
    padding: 1rem;
    background: white;
  }

  .order-table-mobile .col-span-2,
  .order-table-mobile .col-span-3 {
    display: block;
    width: 100%;
    margin-bottom: 0.5rem;
  }

  .order-table-mobile .text-center {
    text-align: left;
  }
}
</style>
